package funcktion;

import tools.BookUpdateGUI;
import tools.UserAddGUI;
import tools.UserUpdateGUI;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserManage extends JFrame {
    private JTable userTable;
    private BookTableModel tableModel;

    public UserManage() {
        // 设置窗口标题
        setTitle("user管理系统");

        // 创建表格模型和表格对象
        tableModel = new BookTableModel();
        userTable = new JTable(tableModel);

        // 创建滚动面板，将表格添加到滚动面板中
        JScrollPane scrollPane = new JScrollPane(userTable);

        // 创建删除按钮和修改按钮
        JButton addButton = new JButton("增添");
        JButton deleteButton = new JButton("删除");
        JButton updateButton = new JButton("修改");


        // 添加按钮的点击事件监听器
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = userTable.getSelectedRow();
                if (selectedRow != -1) {
                    //System.out.println(tableModel.getValueAt(selectedRow, 0).getClass());
                    // 获取选中行的图书编号
                    String userId =  String.valueOf(tableModel.getValueAt(selectedRow, 0));
                    //System.out.println(userId.getClass());
                    // 调用删除图书的方法
                    deleteUser(userId);
                    // 刷新表格数据
                    refreshTableData();
                }else {
                    JOptionPane.showMessageDialog(null, "请选择一条数据", "警告", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = userTable.getSelectedRow();
                //System.out.println(selectedRow);
                if (selectedRow != -1) {
                    // 获取选中行的图书编号
                    String userId = String.valueOf(tableModel.getValueAt(selectedRow, 0));
                    UserUpdateGUI GUI = new UserUpdateGUI(userId);
                    GUI.setVisible(true);
                    // 刷新表格数据
                    refreshTableData();
                }else {
                    JOptionPane.showMessageDialog(null, "请选择一条数据", "警告", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                UserAddGUI GUI = new UserAddGUI();
                GUI.setVisible(true);
            }
        });

        // 创建主面板，并设置布局
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板，并设置布局
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(addButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 将主面板添加到窗口中
        add(mainPanel);

        // 设置窗口大小和显示位置
        setSize(800, 400);
        setLocationRelativeTo(null);
//        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 刷新表格数据
        refreshTableData();
    }

    // 从数据库中查询图书数据，并刷新表格数据
    public void refreshTableData() {
        java.util.List<User> users = queryBooksFromDatabase();
        tableModel.setUsers(users);
    }

    // 从数据库中查询图书数据
    private java.util.List<User> queryBooksFromDatabase() {
        java.util.List<User> users = new ArrayList<>();

        // 建立数据库连接
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "lang520520");
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM User")) {

            // 遍历查询结果集，创建 Book 对象并添加到列表中
            while (rs.next()) {
                int userId = rs.getInt("userId");
                String userName = rs.getString("userName");
                String gender = rs.getString("gender");
                int borrowedBooks = rs.getInt("borrowedBooks");
                int maxBorrowedBooks = rs.getInt("maxBorrowedBooks");
                String status = rs.getString("status");

                User user = new User(userId, userName, gender, borrowedBooks, maxBorrowedBooks, status);
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return users;
    }





    // 删除图书
    private void deleteUser(String userId) {

        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "lang520520");
             PreparedStatement stmt = conn.prepareStatement("DELETE FROM User WHERE userId = ?")) {

            // 设置参数并执行删除操作
            stmt.setString(1, userId);
            stmt.executeUpdate();
            JOptionPane.showMessageDialog(null, "删除成功", "操作成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 建立数据库连接
    }



    // 打开图书编辑对话框
    private void openUpdateBookDialog(String bookId) {
        // 根据图书编号查询数据库，获取图书信息
        // ...

        // 弹出对话框，显示图书信息和编辑表单
        // ...
    }

    // 内部类，表格模型
    private class BookTableModel extends AbstractTableModel {
        private java.util.List<User> users;
        private String[] columnNames = {"用户图书证", "姓名", "性别", "借书量", "借书最大量", "状态"};

        public void setUsers(List<User> users) {
            this.users = users;
            fireTableDataChanged();
        }

        @Override
        public int getRowCount() {
            return users != null ? users.size() : 0;
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (users == null || rowIndex >= users.size()) {
                return null;
            }

            User user = users.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return user.getUserId();
                case 1:
                    return user.getUserName();
                case 2:
                    return user.getGender();
                case 3:
                    return user.getBorrowedBook();
                case 4:
                    return user.getMaxBorrowedBook();
                case 5:
                    return user.getStatus();
                default:
                    return null;
            }
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
    }

    // 内部类，人员
    private class User {
        private int userId;
        private String userName;
        private String gender;
        private int borrowedBooks;
        private int MaxBorrowedBooks;
        private String status;

        public User(int userId, String userName, String price, int borrowedBooks, int MaxBorrowedBooks, String status) {
            this.userId = userId;
            this.userName = userName;
            this.gender = price;
            this.borrowedBooks = borrowedBooks;
            this.MaxBorrowedBooks = MaxBorrowedBooks;
            this.status = status;
        }

        public int getUserId() {
            return userId;
        }

        public String getUserName() {
            return userName;
        }

        public String getGender() {
            return gender;
        }

        public int getBorrowedBook() {
            return borrowedBooks;
        }

        public int getMaxBorrowedBook() {
            return MaxBorrowedBooks;
        }

        public String getStatus() {

            return status;
        }
    }
}
